<template>
  <el-dialog
    v-el-drag-dialog
    title="限时配送设置"
    :visible.sync="visible"
    width="1100px"
    @closed="reset"
  >
    <el-form ref="dataForm" :rules="rules" :model="temp" inline>
      <el-form-item label="月份:" required>
        <el-form-item prop="beginMonth" style="width: 65px;">
          <el-select v-model="temp.beginMonth">
            <el-option v-for="item in 12" :key="item" :value="item" :label="item" />
          </el-select>
        </el-form-item>
        <span>—</span>
        <el-form-item prop="endMonth" style="width: 65px;">
          <el-select v-model="temp.endMonth">
            <el-option v-for="item in 12" :key="item" :value="item" :label="item" />
          </el-select>
        </el-form-item>
      </el-form-item>
      <el-form-item label="配送时段:" prop="time">
        <el-time-picker
          v-model="temp.time"
          is-range
          range-separator="至"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          placeholder="选择时间范围"
          format="HH:mm"
          style="width: 200px;"
        />
      </el-form-item>
      <el-form-item label="预警时间:" prop="warnMinutes">
        <el-input-number v-model="temp.warnMinutes" :min="0" :max="600" :precision="0" :controls="false" style="width: 60px;" /> 分钟
      </el-form-item>
      <el-form-item label="超时时间:" prop="maxMinutes">
        <el-input-number v-model="temp.maxMinutes" :min="0" :max="600" :precision="0" :controls="false" style="width: 60px;" /> 分钟
        <el-button type="primary" style="margin-left: 10px;" @click="add">添加</el-button>
      </el-form-item>
    </el-form>
    <lb-table
      ref="lbTable"
      border
      :column="tableData.column"
      :data="tableData.data"
      :pagination="false"
      :height="200"
    />
    <div slot="footer" class="dialog-footer">
      <el-button @click="visible = false">
        关闭
      </el-button>
      <el-button :loading="$loadingPlugin.submit" type="primary" @click="success">
        保存
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
  import { saveSendTimeLimit } from '@/api'
  import moment from 'dayjs'

  export default {
    name: 'Add',
    data() {
      return {
        visible: false,
        currentOrg: null,
        temp: {
          beginMonth: 1,
          endMonth: 12,
          time: '',
          warnMinutes: undefined,
          maxMinutes: undefined
        },
        rules: {
          time: [{ required: true, message: '请选择配送时段', trigger: 'change' }],
          warnMinutes: [{ required: true, message: '请输入预警时间', trigger: 'blur' }],
          maxMinutes: [{ required: true, message: '请输入超时时间', trigger: 'blur' }]
        },
        tableData: {
          column: [
            {
              prop: 'beginMonth',
              label: '月份',
              render: (h, { row }) => <span>{row.beginMonth} ~ {row.endMonth}月</span>
            },
            {
              prop: 'startTime',
              label: '配送时段',
              render: (h, { row }) => <span>{moment(row.beginTime).format('HH:mm')} ~ {moment(row.endTime).format('HH:mm')}</span>
            },
            {
              prop: 'warnMinutes',
              label: '预警时间(分钟)',
              align: 'right'
            },
            {
              prop: 'maxMinutes',
              label: '超时时间(分钟)',
              align: 'right'
            },
            {
              label: '操作',
              align: 'center',
              width: 50,
              render: (h, { row, $index }) => {
                return (
                  <div>
                    <el-link size='mini' underline={false} type='danger' onClick={() => this.delRow(row, $index)}>
                      删除
                    </el-link>
                  </div>
                )
              }
            }
          ],
          data: []
        }
      }
    },
    methods: {
      open(org) {
        return new Promise(resolve => {
          this.resolve = resolve
          this.visible = true
          this.currentOrg = org
        })
      },
      add() {
        this.$refs.dataForm.validate(valid => {
          if (!valid) return
          if (this.temp.beginMonth > this.temp.endMonth) {
            this.$message.error('结束月份应大于开始月份')
            return
          }
          if (this.temp.warnMinutes * 1 >= this.temp.maxMinutes * 1) {
            this.$message.error('预警时间应小于超时时间')
            return
          }
          if (moment(this.temp.time[0]).valueOf() >= moment(this.temp.time[1]).valueOf()) {
            this.$message.error('配送结束时间应大于开始时间')
            return
          }
          const row = {
            beginMonth: this.temp.beginMonth,
            endMonth: this.temp.endMonth,
            beginTime: this.temp.time[0],
            endTime: this.temp.time[1],
            warnMinutes: this.temp.warnMinutes,
            maxMinutes: this.temp.maxMinutes
          }
          if (this.tableData.data.find(item => item.beginMonth === this.temp.beginMonth && item.endMonth === this.temp.endMonth &&
            item.beginTime === this.temp.time[0] && item.endTime === this.temp.time[1])) {
            const index = this.tableData.data.findIndex(item => item.beginMonth === this.temp.beginMonth && item.endMonth === this.temp.endMonth &&
              item.beginTime === this.temp.beginTime && item.endTime === this.temp.endTime)
            this.tableData.data.splice(index, 1, row)
          } else this.tableData.data.push(row)
        })
      },
      // 删除行
      delRow(scope) {
        this.tableData.data.splice(scope.$index, 1)
      },
      success() {
        if (this.tableData.data.length === 0) {
          this.$message.error('请添加一条记录')
          return
        }
        if (this.tableData.data.length > 10) {
          this.$message.error('最多只能添加10条')
          return
        }
        const postData = []
        this.tableData.data.forEach(item => {
          const obj = {}
          obj.beginMonth = item.beginMonth
          obj.endMonth = item.endMonth
          obj.beginTime = moment('2000-01-01 ' + moment(item.beginTime).format('HH:mm:ss')).format()
          obj.endTime = moment('2000-01-01 ' + moment(item.endTime).format('HH:mm:ss')).format()
          obj.warnMinutes = item.warnMinutes
          obj.maxMinutes = item.maxMinutes
          obj.orgId = this.currentOrg.orgId
          postData.push(obj)
        })
        this.submit(postData)
      },
      async submit(postData) {
        await saveSendTimeLimit(postData)
        this.resolve()
        this.visible = false
        this.$notify({
          title: '提示',
          message: '操作成功',
          type: 'success',
          duration: 2000
        })
      },
      reset() {
        this.temp = {
          beginMonth: 1,
          endMonth: 12,
          time: '',
          warnMinutes: undefined,
          maxMinutes: undefined
        }
        this.tableData.data = []
        this.$nextTick(() => {
          this.$refs.dataForm.clearValidate()
        })
      }
    }
  }
</script>

<style lang="scss" scoped>
.form {
  display: flex;
  flex-wrap: wrap;
  & /deep/ .el-form-item {
    width: 50%;
    padding-right: 10px;
    .el-form-item__content > .el-select {
      width: 100%;
    }
  }
  .block {
    width: 100%;
  }
}
</style>
